package cs;

import handler.BlockingHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;
import vip.ipav.log.util.LoggerTools;

import java.io.IOException;
import java.net.InetSocketAddress;


public class NonBlockingIoExample {

    /**
     * Listing 1.1 Blocking I/O example
     * */
    public void serve(int portNumber) throws IOException, InterruptedException {
        //设置服务相关参数
        final BlockingHandler serverHandler = new BlockingHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(group)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(portNumber))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(serverHandler);
                    }
                });
        //开启服务
        try {
            //创建新Channel,并返回同步的结果集
            ChannelFuture f = b.bind().sync();
            System.out.println(NonBlockingIoExample.class.getName() +
                    " started and listening for connections on " + f.channel().localAddress());
            //等待关闭指令
            f.channel().closeFuture().sync();
            LoggerTools.getConsoleLogger().info("ChanelFuture is Done:{}",f.isDone());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully().sync();
            LoggerTools.getConsoleLogger().info("收到关闭指令，销毁相关资源！");
        }

        Runtime.getRuntime().addShutdownHook(new Thread(()-> {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
    }

    private String processRequest(String request){
        return "Processed";
    }
}
